<template>
    <el-card shadow="never" class="border-0">

        <!-- 新增|刷新 -->
        <div class="flex items-center  mb-4">
            <el-button v-if="props.isEdit == true" type="primary" size="small" @click="clickAddBtn(0)">节点新增</el-button>
            <el-button v-else type="primary" size="small" disabled>节点新增</el-button>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="tableDataLoading">

            <el-table-column prop="maxApprovalTime" label="审批人" #default="{ row }" align="center">
                已选{{ row.approverIds.split(",").length }}人
            </el-table-column>
            
            <el-table-column prop="approvalType" label="审批类型" #default="{ row }" align="center">
                {{ row.approvalType=="1"?"或签":"会签" }}
            </el-table-column>

            <!-- <el-table-column prop="maxApprovalTime" label="最大审批时间(小时)" #default="{ row }" align="center">
                {{ row.maxApprovalTime }}
            </el-table-column> -->

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="240">
                <template #default="scope">
                    <div class="flex flex-row ">
                        <el-button v-if="props.isEdit == true" type="primary" size="small" text @click="clickEditBtn(scope.row)">修改</el-button>
                        <el-button v-else type="primary" size="small" text disabled>修改</el-button>

                        <el-button type="primary" size="small" text @click="showApprovalPersonBtn(scope.row)">查看审核人</el-button>
                        <el-popconfirm title="是否要删除该节点？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="clickDeleteBtn(scope.row.nodeId)">
                            <template #reference>
                                <el-button v-if="props.isEdit == true" text type="primary" size="small">删除</el-button>
                                <el-button v-else text type="primary" size="small" disabled>删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增 更新 抽屉 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="clickDrawerSubmitBtn" size="40%">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="150px" :inline="false">

                <el-form-item required label="审核人" prop="approverIds">
                    <el-button style="width: 100%;" v-if="form.approverIds.length == 0" @click="showDialogTableVisible_approvalPerson(i,form.approverIds)">审批人</el-button>
                    <el-button style="width: 100%;" v-else @click="showDialogTableVisible_approvalPerson(i,form.approverIds)">已选{{ form.approverIds.length }}人</el-button>
                </el-form-item>

                <el-form-item required label="审批类型" prop="approvalType">
                    <el-select style="width: 100%;" v-model="form.approvalType" placeholder="审批类型">
                        <el-option key=1 label="或签" value=1></el-option>
                        <el-option key=2 label="会签" value=2></el-option>
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="最大审批时间(小时)" prop="maxApprovalTime">
                    <el-input style="width: 100%;" v-model="form.maxApprovalTime" placeholder="审批时间(小时)" type="text" @input="(v)=>(form.maxApprovalTime=v.replace(/[^\d]/g,''))" />
                </el-form-item> -->
            </el-form>
        </FormDrawer>
    </el-card>


    <!-- 选择审批人 -->
    <el-dialog v-model="dialogTableVisible_approvalPerson" title="选择审批人" width="80%" align-center>
      <SelectApprovalPerson v-if="dialogTableVisible_approvalPerson" :ids="currentApprovalNodeIds" @getCheckedApprovalPerson="getCheckedApprovalPerson" />
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="dialogTableVisible_approvalPerson = false">
                  确认
              </el-button>
          </div>
      </template>
    </el-dialog>

    <!-- 选择审批人 -->
    <el-dialog v-model="showApprovalPerson" title="已选审核人信息" width="50%" align-center>
      <span>{{ approverNames }}</span>
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="showApprovalPerson = false">
                  确认
              </el-button>
          </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import FormDrawer from '~/components/FormDrawer.vue'
import { toast } from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import SelectApprovalPerson from "~/components/select-approval-person.vue";
import { getApprovalNodesByTid,addApprovalNode,updateApprovalNode,deleteApprovalNode } from "~/api/approvalApi"
import { getApprovalPersonByIds } from "~/api/manager";


// 接收父组件参数
const props = defineProps({
    templateId: Number,
    isEdit: {
        type: Boolean,
        default: true
    }
})

//选择审批人弹窗
const dialogTableVisible_approvalPerson = ref(false)
//当前正在操作的节点回显IDS
const currentApprovalNodeIds = ref([])

//查看审核人
const showApprovalPerson = ref(false)
//查看审核人用户名显示
const approverNames = ref('')

// 页面变量
const tableData = ref([]) // 列表数据
const tableDataLoading = ref(false)
const rules = {
    // maxApprovalTime: [
    //      { required: true, message: '最大审批时间不能为空', trigger: 'change' }
    // ],
    approvalType: [
        { required: true, message: '审批类型不能为空', trigger: 'change' }
    ],
    approverIds: [
        { required: true, message: '审核人不能为空', trigger: 'change' }
    ]
    
}

const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")

//表单
const form = reactive({
    id: editId.value,
    templateId: props.templateId,
    approverIds: [], 
    //maxApprovalTime: null, 
    approvalType: null
})
const formRef = ref(null)
const formDrawerRef = ref(null)

// 生命周期
onMounted(() => {
    //加载表格数据
    getData()
})

//获取列表数据
function getData(p = null) {
    tableDataLoading.value = true
    getApprovalNodesByTid(props.templateId)
        .then(res => {
            if(res){
                tableData.value = res.nodeDtoList
            }else{
                tableData.value = []  
            }
        })
        .finally(() => {
            tableDataLoading.value = false
        })
}

//重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

//点击新增角色抽屉中 提交按钮
const clickDrawerSubmitBtn = () => {
    // console.log(JSON.stringify(form))
    formRef.value.validate((valid) => {
        if (!valid) return
        formDrawerRef.value.showLoading()
        const fun = editId.value ? updateApprovalNode(editId.value, form) : addApprovalNode(form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).catch(err => {

        }).finally(() => {
            formDrawerRef.value.hideLoading()
        })
    })
}

// 编辑
const clickEditBtn = (row) => {
    //清空校验信息
    if (formRef.value) formRef.value.resetFields()
    editId.value = row.nodeId
    //回显赋值
    currentApprovalNodeIds.value = row.approverIds.split(",")
    form.approverIds = row.approverIds.split(",")
    //form.maxApprovalTime = row.maxApprovalTime
    form.approvalType = row.approvalType.toString()
    //console.log(JSON.stringify(form))
    formDrawerRef.value.open()
}

// 查看审核人
const showApprovalPersonBtn = (row) => {
    //显示审核人
    let paramIo = {}
    paramIo.ids = row.approverIds.split(",")
    getApprovalPersonByIds(paramIo)
        .then(res => {
        if(res){
            approverNames.value = res.map(user => {
                return user.username+"("+user.phone+")";
            }).join('; ');
        }
    })
    //显示弹框
    showApprovalPerson.value = true
}

// 新增
const clickAddBtn = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        approverIds: [], 
        templateId: props.templateId,
        //maxApprovalTime: null, 
        approvalType: null
    })
    formDrawerRef.value.open()
}

// 删除
const clickDeleteBtn = (id) => {
    tableDataLoading.value = true

    let paramIo = {templateId:props.templateId,nodeId:id}
    deleteApprovalNode(paramIo).then(res => {
        toast("删除成功")
        getData()
    }).catch(err => {

    }).finally(() => {
        tableDataLoading.value = false
    })
}

//打开选择审核人弹窗
function showDialogTableVisible_approvalPerson(i,obj) {
    dialogTableVisible_approvalPerson.value = true
    //回显赋值
    currentApprovalNodeIds.value = obj
}

//获取选择的审批人
function getCheckedApprovalPerson(ids) {
  if (ids != null) {
    form.approverIds = ids
  }
}
</script>